#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int tickets = 1000;

void *start_routine(void *args)
{
    std::string s = (const char *)args;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            //usleep(1000);

            cout << s << "正在抢票..." << tickets-- << endl;
            //usleep(1000);
            pthread_mutex_unlock(&mutex);
            usleep(1000);
        }
        else
        {
            pthread_mutex_unlock(&mutex);

            break;
        }
    }
    return nullptr;
}

int main()
{
    // int a = 7;
    // printf("%d\n",a);

    pthread_t t;
    pthread_t t1;
    pthread_t t2;
    pthread_t t3;
    pthread_t t4;

    pthread_create(&t, nullptr, start_routine, (void *)"thread 1");
    pthread_create(&t1, nullptr, start_routine, (void *)"thread 2");
    pthread_create(&t2, nullptr, start_routine, (void *)"thread 3");
    pthread_create(&t3, nullptr, start_routine, (void *)"thread 4");
    pthread_create(&t4, nullptr, start_routine, (void *)"thread 5");

    // while(1)
    // {
    //     std::cout<<"主线程..."<<std::endl;
    //     sleep(1);
    // }

    pthread_join(t, nullptr);
    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}